<?php
/**
 * Classe Code promo
 *
 * Description de la classe
 *
 * @author Mathieu
 */
class ReductionCode extends Object {
    protected $id;
    protected $id_liste;
    protected $code;
    protected $nb_utilisation;
    protected $etat;

    protected $list;
   
	function __construct($id="", $params=array()) {
        if($id!='') {
            $this->id = $id;
            foreach($params as $key => $p) {
                $this->$key = $p;
            }
        }
    }
	function __toString() {
        if(!isset($this->code)) $this->load();
        return $this->code;
    }
	
	public function load() {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM code_promo WHERE id = '".$this->id."'");
        if(sizeof($result) > 0) {
            foreach($result[0] as $key => $p) {
                $this->$key = $p;
            }
            return;
        }
        if(DEBUG) echo("Objet inconnu");
        return false;
    }

    public function isValid(){
		if($this->etat!=1) return 1;
        if($this->nb_utilisation>=$this->list['utilisation']) return 1;
		if($this->list['date_valid']<date("Y-m-d")&&$this->list['date_valid']!='0000-00-00') return 2;
        return true;

	}
	
	public static function get($code){
        $db = Database::getInstance();
        $sql ="SELECT code_promo.id as id_code, liste_code.id as id_liste, code_promo.code as code, code_promo.nb_utilisation as nb_utilisation, code_promo.etat as etat FROM code_promo INNER JOIN liste_code ON liste_code.id=code_promo.id_liste WHERE code = '".$code."'";
        $result = $db->query($sql);
		if(sizeof($result) > 0) {
			foreach($result as $line){
                $list = new ListReductionCode($line['id_liste'], $line);
				return new ReductionCode($line['id_code'], array('id_liste'=>$line['id_liste'],
                                                                 'code'=>$line['code'],
                                                                 'nb_utilisation'=>$line['nb_utilisation'],
                                                                 'etat'=>$line['etat'],
                                                                 'list'=>$list));
			}
		}
		return false;
    }
}